import React, { useState, forwardRef, useImperativeHandle } from 'react';
import { Modal, ModalProps } from 'antd';

const defaultModalOptions = {
  title: '错误消息',
  width: 500,
  footer: null
};

type OptionsObjType = ModalProps & { message: string };
type ShowOptions = string | OptionsObjType;

export interface ModalErrorRef {
  show(options: ShowOptions): void;
}

export default forwardRef((_, ref: React.Ref<ModalErrorRef>) => {
  const [visible, setVisible] = useState(false);
  const [message, setMessage] = useState('');
  const [customOptions, setCustomOptions] = useState<ModalProps>(defaultModalOptions);

  useImperativeHandle(ref, () => ({
    show: (options: ShowOptions) => {
      if (typeof options === 'string') {
        setMessage(options);
      } else if (Object.prototype.toString.call(options) === '[object Object]') {
        const { message: msg, ...modalProps } = (options as Record<string, any>) || {};
        setMessage(msg);
        setCustomOptions({ ...defaultModalOptions, ...modalProps });
      }
      setVisible(true);
    }
  }));

  return (
    <Modal {...customOptions} visible={visible} onCancel={() => setVisible(false)}>
      {message}
    </Modal>
  );
});
